package application

import (
	"awesomeProject/handle"
	"awesomeProject/logger"
	"awesomeProject/models"
)

var lg = logger.InitLog()

func InitFun() {

	db, err := models.ConnectDB()
	if err != nil {
		lg.Error("Error connecting to database:", err)
		return
	}
	defer db.Close()

	//
	// 查询请求
	//
	lg.Debugf("update token...")
	var klconfig *models.KLConfig
	klconfig, _ = models.KLConfigInfo(db)

	accessToken, err := handle.GetToken(klconfig.GrantType, klconfig.ClientID, klconfig.ClientSecret)
	if err != nil {
		lg.Error("getToken:", err)
		return
	}

	klconfig.AccessToken = accessToken.AccessToken
	err = models.KLConfigUpdate(db, accessToken.AccessToken, klconfig.ID)
	if err != nil {
		lg.Error("Error KLConfigUpdate updating token:", err)
		return
	}
	// 查询appids
	lg.Debug("update openid...")
	appids, err := handle.GetOpenID(klconfig.AppID, klconfig.AccessToken)
	if err != nil {
		lg.Debug("getOpenID error:", err)
		return
	}
	lg.Debug("create openid or exits")
	exists, err := models.OpenInsTableExists(db)
	lg.Debugf("exists: %v", exists)
	if err != nil {
		lg.Error("create openid :", err)
		// return
	}
	if !exists {
		lg.Debug("create openid")
		err = models.OpenInsCreateTable(db)
		if err != nil {
			lg.Error("Error creating OpenIns table:", err)
			return
		}
		lg.Debug("insert openid")
		for _, appid := range appids {
			// 保存到OpenIns
			err := models.OpenInsInsert(db, appid.OpenId, appid.Title)
			if err != nil {
				lg.Error("Error inserting OpenIns:", err)
				return
			}
		}
	}

	// 查询detail
	lg.Debug("update openid detail...")
	existsOpenDetail, err := models.OpenInsDetailTableExist(db)
	lg.Debugf("existsOpenDetail: %v", existsOpenDetail)
	if err != nil {
		lg.Error("create existsOpenDetail :", err)
		// return
	}
	if !existsOpenDetail {
		err := models.OpenInsDetailCreateTable(db)
		if err != nil {
			lg.Error("Error create existsOpenDetail:", err)
			return
		}
		for _, appid := range appids {

			detail, err := handle.GetOpenDetail(klconfig.AppID, klconfig.AccessToken, appid.OpenId)

			if err != nil {
				lg.Error("getOpenDetail Error:", err)
				return
			}
			for _, detailcontent := range detail.Content.Passageways {
				for _, device := range detailcontent.DevicesOpenID {
					err := models.OpenInsDetailInsert(db, detail.Content.OpenId, detail.Content.Title, detailcontent.PassagewayId, device.OpenId)
					if err != nil {
						lg.Error("Error inserting OpenInsDetail:", err)
						return
					}
				}
			}
		}
	}

}
